// src/api/BaseApi.ts
import axios, { type AxiosInstance, type AxiosResponse, type AxiosError } from 'axios';
import type { ApiResponse } from '../types/DataTypes.ts';

// 基础API客户端类
export class BaseApiClient {
    protected client: AxiosInstance;

    constructor(baseURL: string = import.meta.env.VITE_API_BASE_URL) {
        this.client = axios.create({
            baseURL,
            timeout: 10000,
            headers: {
                'Content-Type': 'application/json',
            },
        });

        this.setupInterceptors();
    }

    // 设置拦截器
    private setupInterceptors(): void {
        // 请求拦截器
        this.client.interceptors.request.use(
            (config) => {
                console.log(`🚀 发送请求: ${config.method?.toUpperCase()} ${config.url}`);
                return config;
            },
            (error) => {
                console.error('❌ 请求错误:', error);
                return Promise.reject(error);
            }
        );

        // 响应拦截器
        this.client.interceptors.response.use(
            (response: AxiosResponse) => {
                console.log(`✅ 收到响应: ${response.status} ${response.config.url}`);
                return response;
            },
            (error: AxiosError) => {
                console.error('❌ 响应错误:', error.response?.status, error.message);
                return Promise.reject(error);
            }
        );
    }

    // 通用请求方法
    protected async request<T>(config: any): Promise<ApiResponse<T>> {
        try {
            const response = await this.client.request<ApiResponse<T>>(config);
            return response.data;
        } catch (error: any) {
            if (error.response) {
                // 服务器返回错误
                return {
                    success: false,
                    message: error.response.data?.message || '请求失败',
                    error: error.response.data?.error,
                };
            } else if (error.request) {
                // 网络错误
                return {
                    success: false,
                    message: '网络连接错误，请检查网络设置',
                };
            } else {
                // 其他错误
                return {
                    success: false,
                    message: error.message || '未知错误',
                };
            }
        }
    }
}